package app.remote.repository;

import app.remote.entity.RssUrl;
import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: haibo.wang
 * Date: 13-7-9
 * Time: 下午3:40
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class RssRepository {
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private RestTemplate rssTemplate;

    public List<RssUrl> getHello() {
        List<RssUrl> urls = jdbcTemplate.query("select * from rss_url", (ResultSet rs, int i) -> {
            RssUrl url = new RssUrl();
            url.setId(rs.getInt("id"));
            url.setName(rs.getString("name"));
            url.setUrl(rs.getString("url"));
            return url;
        });
        return urls;
    }

    public void addUrl(RssUrl rssUrl) {
        jdbcTemplate.update("insert into rss_url(name,url) values (?,?)", rssUrl.getName(), rssUrl.getUrl());
    }

    public Channel getRssInfo(int id) {
        String rssUrl = jdbcTemplate.queryForObject("select url from rss_url where id=?", String.class, id);
        Channel channel = rssTemplate.getForObject(rssUrl, Channel.class);
        return channel;
    }

    public void deleteUrl(int id) {
        jdbcTemplate.update("delete from rss_url where id=?", id);
    }
}
